from unicodedata import name
from fastapi import Body, FastAPI, File, Form, UploadFile
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import mysql.connector
from translation import *
from participle import *
from idiom_translation import *

app = FastAPI() # 创建 api 对象

# 登录对象
class LoginForm(BaseModel):
    username: str
    password: str
# 翻译对象
class TranslateFrom(BaseModel):
    sourceText: str
    sourceLang: str
    targetLang: str
# 分词对象
class SegmentFrom(BaseModel):
    inputText: str

# 成语翻译对象
class IdiomsForm(BaseModel):
    inputText: str
      

# 跨域设置
app.add_middleware(
	CORSMiddleware,
	# 允许跨域的源列表
	allow_origins=["*"],
	# 跨域请求是否支持 cookie，默认是 False，如果为 True，allow_origins 必须为具体的源，不可以是 ["*"]
	allow_credentials=False,
	# 允许跨域请求的 HTTP 方法列表，默认是 ["GET"]
	allow_methods=["*"],
	# 允许跨域请求的 HTTP 请求头列表，默认是 []，可以使用 ["*"] 表示允许所有的请求头
	allow_headers=["*"],
)

def getConnection():
    conn = mysql.connector.connect(
        host='localhost',
        user='root',
        password='root',
        database='nlp'
    )
    return conn

# 连接到MySQL数据库


# 登录请求
@app.post("/login")
def login(login_form: LoginForm):
    username = login_form.username
    password = login_form.password
    user = None
    if parsee.database:
        conn = getConnection()
        # 创建游标对象
        cursor = conn.cursor()
        # 执行查询语句
        cursor.execute("SELECT * FROM user WHERE username = %s AND password = %s", (username, password))
        # 获取查询结果
        user = cursor.fetchone()
        # 关闭游标
        cursor.close()
        conn.close()
    if user or not parsee.database:
        return {"code": 200, "msg": "用户登录成功"}
    else:
        return {"code": 203, "msg": "登录失败，请重新输入"}


# 翻译请求
@app.post("/translate")
def login(translate_from: TranslateFrom):
    sourceText = translate_from.sourceText
    sourceLang = translate_from.sourceLang
    targetLang = translate_from.targetLang
    # print(sourceText)
    # print(sourceLang)
    # print(targetLang)
    translationResult, sencent = translate(sourceText, targetLang)

    if parsee.database:
        conn = getConnection()
        # 创建数据库游标
        cursor = conn.cursor()
        # 插入翻译记录到数据库表 history
        query = "INSERT INTO history (sourceLang, targetLang, sourceText, translationResult) VALUES (%s, %s, %s, %s)"
        cursor.execute(query, (sourceLang, targetLang, sourceText, translationResult))
        # 提交事务
        conn.commit()
        # 关闭游标
        cursor.close()
        conn.close()
    return {"code": 200, "msg": "翻译成功", "data": [translationResult, sencent]}

# 分词请求
@app.post("/words")
def login(segmen_from: SegmentFrom):
    inputText = segmen_from.inputText
    words = participle(inputText)
    if parsee.database:
        conn = getConnection()
        # 创建数据库游标
        cursor = conn.cursor()
        # 插入分词记录到数据库表 history
        query = "INSERT INTO words (inputText, words) VALUES (%s, %s)"
        cursor.execute(query, (inputText, words))
        # 提交事务
        conn.commit()
        # 关闭游标
        cursor.close()
        conn.close()
    return {"code": 200, "msg": "分词成功", "data": words}

# 提取关键词请求
@app.post("/keywords")
def login(segmen_from: SegmentFrom):
    inputText = segmen_from.inputText
    keywords = get_keywords(inputText)
    # if parsee.database:
    #     conn = getConnection()
    #     # 创建数据库游标
    #     cursor = conn.cursor()
    #     # 插入提取记录到数据库表 history
    #     query = "INSERT INTO keywords (inputText, keywords) VALUES (%s, %s)"
    #     cursor.execute(query, (inputText, keywords))
    #     # 提交事务
    #     conn.commit()
    #     # 关闭游标
    #     cursor.close()
    #     conn.close()
    return {"code": 200, "msg": "提取成功", "data": keywords}

# 成语翻译
@app.post("/idioms")
def getIdioms(idioms_form: IdiomsForm):
    input = idioms_form.inputText
    print(input)
    idioms = search_idioms_in_text(input)
    print(idioms)
    return {"code": 200, "msg": "分词成功", "data": idioms}

# 历史翻译
@app.get("/translationHistory")
def translationHistory():
    if parsee.database:
        conn = getConnection()
        # 创建数据库游标
        cursor = conn.cursor()
        # 查询最近添加的 5 条翻译历史记录
        query = "SELECT sourceLang, targetLang, sourceText, translationResult FROM history ORDER BY id DESC LIMIT 5"
        cursor.execute(query)
        # 获取查询结果
        history = cursor.fetchall()
        # print(history)
        # 关闭游标
        cursor.close()
        conn.close()
    return {"code": 200, "msg": "查询成功", "data": history}

# 识别请求
@app.post("/langdete")
def login(segmen_from: SegmentFrom):
    inputText = segmen_from.inputText
    langdet = language_detect(inputText)
    # if parsee.database:
    #     conn = getConnection()
    #     # 创建数据库游标
    #     cursor = conn.cursor()
    #     # 插入识别记录到数据库表 history
    #     query = "INSERT INTO words (inputText, words) VALUES (%s, %s)"
    #     cursor.execute(query, (inputText, words))
    #     # 提交事务
    #     conn.commit()
    #     # 关闭游标
    #     cursor.close()
    #     conn.close()
    return {"code": 200, "msg": "识别成功", "data": langdet}

# 分词历史
@app.get("/langdetsHistory")
def langdetHistory():
    if parsee.database:
        conn = getConnection()
        # 创建数据库游标
        cursor = conn.cursor()
        # 查询最近添加的 5 条翻译历史记录
        query = "SELECT inputText, langdet FROM langdets ORDER BY id DESC LIMIT 5"
        cursor.execute(query)
        # 获取查询结果
        langdet = cursor.fetchall()
        # print(langdets)
        # 关闭游标
        cursor.close()
        conn.close()
    return {"code": 200, "msg": "分词成功", "data": langdet}

# 分词历史
@app.get("/wordsHistory")
def wordsHistory():
    if parsee.database:
        conn = getConnection()
        # 创建数据库游标
        cursor = conn.cursor()
        # 查询最近添加的 5 条翻译历史记录
        query = "SELECT inputText, words FROM words ORDER BY id DESC LIMIT 5"
        cursor.execute(query)
        # 获取查询结果
        words = cursor.fetchall()
        # print(words)
        # 关闭游标
        cursor.close()
        conn.close()
    return {"code": 200, "msg": "分词成功", "data": words}

# 提取历史
@app.get("/keywordsHistory")
def keywordsHistory():
    if parsee.database:
        conn = getConnection()
        # 创建数据库游标
        cursor = conn.cursor()
        # 查询最近添加的 5 条翻译历史记录
        query = "SELECT inputText, words FROM keywords ORDER BY id DESC LIMIT 5"
        cursor.execute(query)
        # 获取查询结果
        keywords = cursor.fetchall()
        # print(keywords)
        # 关闭游标
        cursor.close()
        conn.close()
    return {"code": 200, "msg": "分词成功", "data": keywords}

# uvicorn login:app
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)